package com.ziyia.xmltest;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private final String T = getClass().getName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    public void PullParse(View view) {
        OkHttpClient client = new OkHttpClient();


        new Thread(() -> {
            try {
                Request request = new Request.Builder()
                        .url("http://test.ziyia.cn/get_data.xml")
                        .build();
                Response response = client.newCall(request).execute();
                if (response.body() != null) {
                    String res = response.body().string();
                    Log.d(T, res);
                    parseXMLWithPull(res);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

    }

    public void SaxParse(View view) {
        OkHttpClient client = new OkHttpClient();
        new Thread(() -> {
            try {
                Request request = new Request.Builder()
                        .url("http://test.ziyia.cn/get_data.xml")
                        .build();
                Response response = client.newCall(request).execute();
                if (response.body() != null) {
                    String res = response.body().string();
                    Log.d(T, res);
                    parseXMLWithSAX(res);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    private void parseXMLWithSAX(String xmlData) {
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            XMLReader xmlReader = factory.newSAXParser().getXMLReader();
            MyHanlder myHanlder = new MyHanlder();
            xmlReader.setContentHandler(myHanlder);
            xmlReader.parse(new InputSource(new StringReader(xmlData)));
        } catch (SAXException | ParserConfigurationException | IOException e) {
            e.printStackTrace();
        }
    }

    class MyHanlder extends DefaultHandler {
        private String nodeName = "";

        private StringBuilder id;

        private StringBuilder name;

        private StringBuilder version;

        @Override
        public void startDocument() throws SAXException {
            super.startDocument();
            id = new StringBuilder();
            name = new StringBuilder();
            version = new StringBuilder();
        }

        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            super.startElement(uri, localName, qName, attributes);
            // 获取当前节点名
            nodeName = localName;
//            Log.d(T, "url = " + uri);
//            Log.d(T, "localName = " + localName);
//            Log.d(T, "gName = " + qName);
//            Log.d(T, "attributes = " + attributes);
        }

        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            super.characters(ch, start, length);
            switch (nodeName) {
                case "id":
                    id.append(ch, start, length);
                    break;
                case "name":
                    name.append(ch, start, length);
                    break;
                case "version":
                    version.append(ch, start, length);
                    break;

            }
        }

        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {
            super.endElement(uri, localName, qName);
            if ("app".equals(localName)) {

                String format = String.format("id = %s，name = %s，version = %s", id.toString().trim(), name.toString().trim(), version.toString().trim());
                Log.d("请求响应", format);
            }
        }

        @Override
        public void endDocument() throws SAXException {
            super.endDocument();
        }
    }

    private void parseXMLWithPull(String response) {
        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser xmlPullParser = factory.newPullParser();
            xmlPullParser.setInput(new StringReader(response));
            int eventType = xmlPullParser.getEventType();
            String id = "";
            String name = "";
            String version = "";
            while (XmlPullParser.END_DOCUMENT != eventType) {
                String nodeName = xmlPullParser.getName();
                switch (eventType) {
                    case XmlPullParser.START_TAG:
                        switch (nodeName){
                            case "id":
                                id = xmlPullParser.nextText();
                                break;
                            case "name":
                                name = xmlPullParser.nextText();
                                break;
                            case "version":
                                version = xmlPullParser.nextText();
                                break;
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        if ("app".equals(nodeName)) {
                            Log.d(T, "id = " + id );
                            Log.d(T, "name = " + name );
                            Log.d(T, "version = " + version );
                        }
                        break;
                }
                eventType = xmlPullParser.next();
            }
        } catch (XmlPullParserException | IOException e) {
            e.printStackTrace();
        }
    }
}